package org.zasadnyy.redlions.players.client.ds;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.zasadnyy.redlions.players.shared.model.PlayerItem;
import org.zasadnyy.redlions.players.shared.model.TournamentItem;

import com.smartgwt.client.data.Record;

public class ItemConverter {
	public PlayerItem recordToPlayerItem(Record record) {
		PlayerItem item = new PlayerItem();
		
		item.setBirtday(record.getAttributeAsDate(PlayerItem.BIRTHDAY));
		item.setId(record.getAttribute(PlayerItem.ID));
		item.setName(record.getAttribute(PlayerItem.NAME));
		item.setNativeCity(record.getAttribute(PlayerItem.NATIVE_CITY));
		item.setPhotoUrl(record.getAttribute(PlayerItem.PHOTO_URL));
		item.setPlaysFrom(record.getAttributeAsDate(PlayerItem.PLAYS_FROM));
		item.setSurname(record.getAttribute(PlayerItem.SURNAME));
		
		//Map<Integer, List<TournamentItem>> tournamrnts = recordToTournamentsMap(record);
		//item.setTournaments(tournamrnts);
		
		return item;
	}

	private Map<Integer, List<TournamentItem>> recordToTournamentsMap(Record record) {
		Map<Integer, List<TournamentItem>> tournamentsMap = new HashMap<Integer, List<TournamentItem>>();
		Record tournamentsPerYear = record
				.getAttributeAsRecord(PlayerItem.TOURNAMENTS);
		String[] attributes = tournamentsPerYear.getAttributes();
		List<Integer> years = new ArrayList<Integer>();
		for (String attr : attributes) {
			try {
				Integer iYear = Integer.valueOf(attr);
				years.add(iYear);
			} catch (NumberFormatException e) {

			}
		}

		for (Integer year : years) {
			List<TournamentItem> tournamentsList = new LinkedList<TournamentItem>();

			Record[] tournaments = tournamentsPerYear
					.getAttributeAsRecordArray(year.toString());
			for (int i = 0; i < tournaments.length; i++) {
				TournamentItem tournamentItem = recordToTournmanentItem(tournaments[i]);
				tournamentsList.add(tournamentItem);
			}

			tournamentsMap.put(year, tournamentsList);
		}
		return tournamentsMap;
	}

	private TournamentItem recordToTournmanentItem(Record tournaments) {
		TournamentItem item = new TournamentItem();
		item.setId(tournaments.getAttribute(TournamentItem.ID));
		item.setTime(tournaments.getAttributeAsDate(TournamentItem.TIME));
		item.setTitle(tournaments.getAttribute(TournamentItem.TITLE));
		item.setUrl(tournaments.getAttribute(TournamentItem.URL));
		List<String> playerIdsList = new ArrayList<String>();
		String[] playerIds = tournaments
				.getAttributeAsStringArray(TournamentItem.PLAYERS);
		for (int i = 0; i < playerIds.length; i++) {
			playerIdsList.add(playerIds[i]);
		}
		item.setPlayerIds(playerIdsList);

		return item;
	}
}
